package com.mybatis.mybatisdatab.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HTMLController {

    @RequestMapping({"/","/index"})
    public String getIndex(Model model){
        model.addAttribute("msg","Hello,world!");
        return "index";
    }

    @RequestMapping("user/add")
    public String getAddUser(){

        return "user/add";
    }

    @RequestMapping("user/update")
    public String getUpdate(){
        return "user/update";
    }

    @RequestMapping("toLogin")
    public String goToLogin(){
        return "login";
    }

    @RequestMapping("html/login/{userName}/{password}")
    public String login(@PathVariable("userName") String userName,@PathVariable("password") String password, Model model) {

        //获取当前的用户
        Subject currentUser = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try {
            currentUser.login(token);//执行登录方法，没有异常就说明ok

            model.addAttribute("msg", "用户名:" + userName);
            return "index";
        } catch (UnknownAccountException e) {//用户名不存在
            model.addAttribute("msg", "用户名错误");
            return "login";
        } catch (IncorrectCredentialsException e) {//密码 不存在
            model.addAttribute("msg", "密码错误");
            return "login";
        } catch (ExcessiveAttemptsException e) {
            // TODO: handle exception
            model.addAttribute("msg", "登录失败多次，账户锁定10分钟");
            return "login";
        } catch (AuthenticationException e) {
            // 其他错误，比如锁定，如果想单独处理请单独catch处理
            model.addAttribute("msg", "其他错误：" + e.getMessage());
            return "login";
        }
    }

    @RequestMapping("/noAuth")
    public String goNoAuth(){
        return "noAuth";
    }

}
